package com.dhh.toodledo.dao;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.dhh.toodledo.dao.DataBaseHelper;
import com.dhh.toodledo.model.Task;

public class TaskDAO {
	private DataBaseHelper db;
	
	public TaskDAO(Context ctx){
		db = new DataBaseHelper(ctx);
	}
	
	public TaskDAO(DataBaseHelper db){
		this.db = db;
	}
	
	public boolean addTask(Task task){
		boolean isSuc = false;
		ContentValues initialValues = createContentValues(task);
		try{
			db.openDataBase();
			db.getWritableDatabase().insert("TASKS", null, initialValues);
			isSuc = true;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(db!=null) db.close();
		}
		return isSuc;
	}
	
	public boolean markStar(Long id,long star){
		boolean isSuc = true;
		try{
			db.openDataBase();
			db.getReadableDatabase().execSQL("update tasks set modified="+getStamp()+", star="+star+" where id="+id);
			//TODO update account info
		}catch(Exception e){
			e.printStackTrace();
			isSuc = false;
		}finally{
			if(db!=null) db.close();
		}
		
		return isSuc;
	}
	
	public boolean markDone(Long id,boolean done){
		boolean isSuc = true;
		try{
			db.openDataBase();
			//update task complete time
			String ts = done?getStamp():"0";
			db.getReadableDatabase().execSQL("update tasks set modified="+getStamp()+", completed="+ts+" where id="+id);
			//TODO update account info
		}catch(Exception e){
			e.printStackTrace();
			isSuc = false;
		}finally{
			if(db!=null) db.close();
		}
		
		return isSuc;
	}
	
	public Task getTask(Long id){
		Task task = null;	
		if(id==null)
			return null;
		
		try{
			db.openDataBase();
			String whereSQL = "id='"+id+"'";
			Cursor cursor = db.getReadableDatabase().query(true, "TASKS", Task.getColumns(), whereSQL,null, null, null, null, null);				
			if(cursor!=null && cursor.moveToFirst()){
				task = convertTask(cursor);
			}
			if(cursor!=null)
				cursor.close();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(db!=null) db.close();
		}
		return task;
	}
	
	public List<Task> getAllTaskUnComp(int page){
		int pageCnt = 100;
		int start = pageCnt * (page-1);
		String limit = start+","+pageCnt;
		List<Task> tasks = new ArrayList<Task>();
		try{
			db.openDataBase();
			String whereSQL = "completed<=0";
			Cursor cursor = db.getReadableDatabase().query(true, "TASKS", Task.getColumns(), whereSQL,null, null, null, "modified desc", limit);				
			if(cursor!=null && cursor.moveToFirst()){
				do{
					tasks.add(convertTask(cursor));
				}while(cursor.moveToNext());
			}
			if(cursor!=null)
				cursor.close();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(db!=null) db.close();
		}
		return tasks;
	}
	
	private ContentValues createContentValues(Task task){
		ContentValues values = new ContentValues();
		if(task.getId()!=null)
			values.put("id", task.getId());
		if (task.getTitle() != null)
			values.put("title", task.getTitle());
		if (task.getTag() != null)
			values.put("tag", task.getTag());
		if (task.getFolder() != null)
			values.put("folder", task.getFolder());
		if (task.getContext() != null)
			values.put("context", task.getContext());
		if (task.getGoal() != null)
			values.put("goal", task.getGoal());
		if (task.getLocation() != null)
			values.put("location", task.getLocation());
		if (task.getParent() != null)
			values.put("parent", task.getParent());
		if (task.getChildren() != null)
			values.put("children", task.getChildren());
		if (task.getOrder() != null)
			values.put("order", task.getOrder());
		if (task.getDuedate() != null)
			values.put("duedate", task.getDuedate());
		if (task.getDuedatemod() != null)
			values.put("duedatemod", task.getDuedatemod());
		if (task.getStartdate() != null)
			values.put("startdate", task.getStartdate());
		if (task.getDuetime() != null)
			values.put("duetime", task.getDuetime());
		if (task.getStarttime() != null)
			values.put("starttime", task.getStarttime());
		if (task.getRemind() != null)
			values.put("remind", task.getRemind());
		if (task.getRepeat() != null)
			values.put("repeat", task.getRepeat());
		if (task.getRepeatfrom() != null)
			values.put("repeatfrom", task.getRepeatfrom());
		if (task.getStatus() != null)
			values.put("status", task.getStatus());
		if (task.getLength() != null)
			values.put("length", task.getLength());
		if (task.getPriority() != null)
			values.put("priority", task.getPriority());
		if (task.getStar() != null)
			values.put("star", task.getStar());
		if (task.getModified() != null)
			values.put("modified", task.getModified());
		if (task.getCompleted() != null)
			values.put("completed", task.getCompleted());
		if (task.getAdded() != null)
			values.put("added", task.getAdded());
		if (task.getTimer() != null)
			values.put("timer", task.getTimer());
		if (task.getTimeron() != null)
			values.put("timeron", task.getTimeron());
		if (task.getNote() != null)
			values.put("note", task.getNote());
		if (task.getMeta() != null)
			values.put("meta", task.getMeta());
		return values;
	}
	
	private Task convertTask(Cursor cursor){
		Task task = new Task();
		task.setId(cursor.getLong(0));
		task.setTitle(cursor.getString(1));
		task.setTag(cursor.getString(2));
		task.setFolder(cursor.getLong(3));
		task.setContext(cursor.getLong(4));
		task.setGoal(cursor.getLong(5));
		task.setLocation(cursor.getLong(6));
		task.setParent(cursor.getLong(7));
		task.setChildren(cursor.getLong(8));
		task.setOrder(cursor.getLong(9));
		task.setDuedate(cursor.getLong(10));
		task.setDuedatemod(cursor.getLong(11));
		task.setStartdate(cursor.getLong(12));
		task.setDuetime(cursor.getLong(13));
		task.setStarttime(cursor.getLong(14));
		task.setRemind(cursor.getLong(15));
		task.setRepeat(cursor.getLong(16));
		task.setRepeatfrom(cursor.getLong(17));
		task.setStatus(cursor.getLong(18));
		task.setLength(cursor.getLong(19));
		task.setPriority(cursor.getLong(20));
		task.setStar(cursor.getLong(21));
		task.setModified(cursor.getLong(22));
		task.setCompleted(cursor.getLong(23));
		task.setAdded(cursor.getLong(24));
		task.setTimer(cursor.getLong(25));
		task.setTimeron(cursor.getLong(26));
		task.setNote(cursor.getString(27));
		task.setMeta(cursor.getString(28));
		
		return task;
	}
	
	private String getStamp() throws ParseException{
		Timestamp appointTime=Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date date = df.parse(String.valueOf(appointTime));
		long s=date.getTime();  
		String unixDate=String.valueOf(s).substring(0, 10);
		return unixDate;
	}

}
